<template>
  <div class="dashboard">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalUsers }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-s-cooperation"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalRooms }}</div>
          <div class="stat-label">房间总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-s-order"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalOrders }}</div>
          <div class="stat-label">订单总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-s-flag"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalAppointments }}</div>
          <div class="stat-label">预约总数</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 左侧图表 -->
      <div class="chart-section">
        <div class="chart-card">
          <h3 class="chart-title">订单趋势</h3>
          <div class="chart-content">
            <div class="simple-chart">
              <div class="chart-bars">
                <div v-for="(value, index) in orderTrend" :key="index" class="chart-bar">
                  <div class="bar-value" :style="{ height: (value / maxOrderValue) * 200 + 'px' }">
                    <span class="bar-label">{{ value }}</span>
                  </div>
                  <div class="bar-label">{{ months[index] }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3 class="chart-title">房型分布</h3>
          <div class="chart-content">
            <div class="pie-chart">
              <div v-for="(item, index) in roomDistribution" :key="index" class="pie-item">
                <div class="pie-color" :style="{ backgroundColor: item.color }"></div>
                <div class="pie-info">
                  <span class="pie-name">{{ item.name }}</span>
                  <span class="pie-value">{{ item.value }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧图表 -->
      <div class="chart-section">
        <div class="chart-card">
          <h3 class="chart-title">收入统计</h3>
          <div class="chart-content">
            <div class="simple-chart">
              <div class="chart-bars">
                <div v-for="(value, index) in revenueData" :key="index" class="chart-bar">
                  <div class="bar-value revenue-bar" :style="{ height: (value / maxRevenueValue) * 200 + 'px' }">
                    <span class="bar-label">¥{{ value }}</span>
                  </div>
                  <div class="bar-label">{{ months[index] }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="chart-card">
          <h3 class="chart-title">用户活跃度</h3>
          <div class="chart-content">
            <div class="simple-chart">
              <div class="chart-bars">
                <div v-for="(value, index) in userActivity" :key="index" class="chart-bar">
                  <div class="bar-value activity-bar" :style="{ height: (value / maxActivityValue) * 200 + 'px' }">
                    <span class="bar-label">{{ value }}</span>
                  </div>
                  <div class="bar-label">{{ weekDays[index] }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-tables">
      <div class="table-card">
        <h3 class="table-title">最近订单</h3>
        <el-table :data="recentOrders" style="width: 100%" size="small">
          <el-table-column prop="id" label="订单号" width="80"></el-table-column>
          <el-table-column prop="roomName" label="房间" width="120"></el-table-column>
          <el-table-column prop="memberName" label="客户" width="100"></el-table-column>
          <el-table-column prop="checkInDate" label="入住日期" width="120"></el-table-column>
          <el-table-column prop="checkOutDate" label="退房日期" width="120"></el-table-column>
          <el-table-column prop="totalPrice" label="金额" width="80">
            <template slot-scope="scope">
              ¥{{ scope.row.totalPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="mini">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="table-card">
        <h3 class="table-title">热门房型</h3>
        <el-table :data="popularRooms" style="width: 100%" size="small">
          <el-table-column prop="categoryName" label="房型" width="120"></el-table-column>
          <el-table-column prop="roomCount" label="房间数" width="80"></el-table-column>
          <el-table-column prop="orderCount" label="订单数" width="80"></el-table-column>
          <el-table-column prop="occupancyRate" label="入住率" width="80">
            <template slot-scope="scope">
              {{ scope.row.occupancyRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="avgPrice" label="平均价格" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.avgPrice }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { findAllMemberAPI } from '@/api/member'
import { findAllRoomAPI } from '@/api/room'
import { findOrdersAPI } from '@/api/orders'
import { findAppointmentAPI } from '@/api/appointment'
import { findAllCategoryAPI } from '@/api/category'

export default {
  name: 'Dashboard',
  data() {
    return {
      stats: {
        totalUsers: 0,
        totalRooms: 0,
        totalOrders: 0,
        totalAppointments: 0
      },
      recentOrders: [],
      popularRooms: [],
      // 模拟数据
      orderTrend: [120, 200, 150, 80, 70, 110],
      revenueData: [820, 932, 901, 934, 1290, 1330],
      userActivity: [120, 132, 101, 134, 90, 230, 210],
      months: ['1月', '2月', '3月', '4月', '5月', '6月'],
      weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      roomDistribution: [
        { name: '标准间', value: 35, color: '#ffd700' },
        { name: '豪华间', value: 25, color: '#409EFF' },
        { name: '套房', value: 20, color: '#67C23A' },
        { name: '总统套房', value: 20, color: '#E6A23C' }
      ]
    }
  },
  computed: {
    maxOrderValue() {
      return Math.max(...this.orderTrend)
    },
    maxRevenueValue() {
      return Math.max(...this.revenueData)
    },
    maxActivityValue() {
      return Math.max(...this.userActivity)
    }
  },
  async mounted() {
    await this.loadData()
  },
  methods: {
    async loadData() {
      try {
        // 获取所有数据
        const [members, rooms, orders, appointments, categories] = await Promise.all([
          findAllMemberAPI(),
          findAllRoomAPI(),
          findOrdersAPI({}), // 使用条件查询接口获取完整数据
          findAppointmentAPI(),
          findAllCategoryAPI()
        ])

        // 统计数据
        this.stats.totalUsers = members.data?.length || 0
        this.stats.totalRooms = rooms.data?.length || 0
        this.stats.totalOrders = orders.data?.length || 0
        this.stats.totalAppointments = appointments.data?.length || 0

        // 最近订单
        this.recentOrders = (orders.data || []).slice(0, 10).map(order => ({
          id: order.id,
          roomName: order.room?.roomNum ? `房间${order.room.roomNum}` : '未知房间',
          memberName: order.member?.name || '未知用户',
          checkInDate: this.formatDate(order.startTime),
          checkOutDate: this.formatDate(order.checkOutTime),
          totalPrice: order.money || 0,
          status: order.status
        }))

        // 热门房型统计
        this.popularRooms = this.calculatePopularRooms(rooms.data || [], orders.data || [], categories.data || [])

        // 更新房型分布数据
        this.updateRoomDistribution(categories.data || [])

      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return '未知'
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN')
    },

    calculatePopularRooms(rooms, orders, categories) {
      const roomStats = {}
      
      // 统计每个房型的订单数
      orders.forEach(order => {
        const room = rooms.find(r => r.id === order.roomId)
        if (room) {
          const category = categories.find(c => c.id === room.categoryId)
          if (category) {
            if (!roomStats[category.id]) {
              roomStats[category.id] = {
                categoryName: category.categoryName,
                roomCount: 0,
                orderCount: 0,
                totalPrice: 0
              }
            }
            roomStats[category.id].orderCount++
            roomStats[category.id].totalPrice += parseFloat(order.money) || 0
          }
        }
      })

      // 统计每个房型的房间数
      rooms.forEach(room => {
        const category = categories.find(c => c.id === room.categoryId)
        if (category) {
          if (!roomStats[category.id]) {
            roomStats[category.id] = {
              categoryName: category.categoryName,
              roomCount: 0,
              orderCount: 0,
              totalPrice: 0
            }
          }
          roomStats[category.id].roomCount++
        }
      })

      // 计算入住率和平均价格
      const result = Object.values(roomStats).map(stat => ({
        ...stat,
        occupancyRate: stat.roomCount > 0 ? Math.round((stat.orderCount / (stat.roomCount * 30)) * 100) : 0, // 假设30天
        avgPrice: stat.orderCount > 0 ? Math.round(stat.totalPrice / stat.orderCount) : 0
      })).sort((a, b) => b.orderCount - a.orderCount).slice(0, 5)
      
      return result
    },

    updateRoomDistribution(categories) {
      // 根据实际房型数据更新分布
      if (categories.length > 0) {
        const colors = ['#ffd700', '#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
        
        // 计算每个房型的房间数量
        const categoryStats = categories.map(category => ({
          name: category.categoryName,
          roomCount: category.roomNum || 0,
          color: colors[categories.indexOf(category) % colors.length]
        }))
        
        const totalRooms = categoryStats.reduce((sum, c) => sum + c.roomCount, 0)
        
        this.roomDistribution = categoryStats.slice(0, 5).map(category => ({
          name: category.name,
          value: totalRooms > 0 ? Math.round((category.roomCount / totalRooms) * 100) : 0,
          color: category.color
        }))
      }
    },

    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return statusMap[status] || 'info'
    },

    getStatusText(status) {
      const statusMap = {
        0: '待确认',
        1: '已确认',
        2: '已入住',
        3: '已退房'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style lang="less" scoped>
.dashboard {
  padding: 20px;
  background: linear-gradient(135deg, #232946 0%, #393e46 100%);
  min-height: 100vh;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;

  .stat-card {
    background: rgba(35, 41, 70, 0.92);
    border-radius: 12px;
    padding: 24px;
    display: flex;
    align-items: center;
    border: 1px solid rgba(255, 215, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
      border-color: rgba(255, 215, 0, 0.3);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      background: linear-gradient(135deg, #ffd700, #ffed4e);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;

      i {
        font-size: 28px;
        color: #232946;
      }
    }

    .stat-content {
      .stat-number {
        font-size: 32px;
        font-weight: bold;
        color: #ffd700;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 16px;
        color: #bbb;
      }
    }
  }
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;

  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
  }

  .chart-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .chart-card {
    background: rgba(35, 41, 70, 0.92);
    border-radius: 12px;
    padding: 20px;
    border: 1px solid rgba(255, 215, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
      border-color: rgba(255, 215, 0, 0.3);
    }

    .chart-title {
      color: #ffd700;
      font-size: 18px;
      margin-bottom: 15px;
      font-weight: 600;
    }

    .chart-content {
      .simple-chart {
        height: 300px;
        display: flex;
        align-items: flex-end;
        justify-content: space-around;
        padding: 20px 0;

        .chart-bars {
          display: flex;
          align-items: flex-end;
          justify-content: space-around;
          width: 100%;
          height: 100%;

          .chart-bar {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 40px;

            .bar-value {
              width: 30px;
              background: linear-gradient(to top, #ffd700, #ffed4e);
              border-radius: 4px 4px 0 0;
              display: flex;
              align-items: flex-start;
              justify-content: center;
              padding-top: 5px;
              min-height: 20px;
              transition: all 0.3s ease;
              position: relative;

              &:hover {
                transform: scale(1.1);
                box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
              }

              .bar-label {
                color: #232946;
                font-size: 12px;
                font-weight: bold;
              }
            }

            .bar-label {
              margin-top: 8px;
              color: #bbb;
              font-size: 12px;
            }
          }

          .revenue-bar {
            background: linear-gradient(to top, #409EFF, #67C23A);
          }

          .activity-bar {
            background: linear-gradient(to top, #E6A23C, #F56C6C);
          }
        }
      }

      .pie-chart {
        display: flex;
        flex-direction: column;
        gap: 15px;
        padding: 20px;

        .pie-item {
          display: flex;
          align-items: center;
          gap: 12px;

          .pie-color {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.2);
          }

          .pie-info {
            display: flex;
            justify-content: space-between;
            flex: 1;
            align-items: center;

            .pie-name {
              color: #bbb;
              font-size: 14px;
            }

            .pie-value {
              color: #ffd700;
              font-weight: bold;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
}

.data-tables {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;

  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
  }

  .table-card {
    background: rgba(35, 41, 70, 0.92);
    border-radius: 12px;
    padding: 20px;
    border: 1px solid rgba(255, 215, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
      border-color: rgba(255, 215, 0, 0.3);
    }

    .table-title {
      color: #ffd700;
      font-size: 18px;
      margin-bottom: 15px;
      font-weight: 600;
    }

    /deep/ .el-table {
      background: transparent;
      color: #fff;

      th {
        background: rgba(255, 255, 255, 0.05);
        color: #ffd700;
        border-bottom: 1px solid rgba(255, 215, 0, 0.2);
      }

      td {
        background: transparent;
        color: #bbb;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      }

      tr:hover > td {
        background: rgba(255, 255, 255, 0.05);
      }
    }
  }
}
</style> 